#include "StdAfx.h"
#include "TestRunMonitorThread.h"


CTestRunMonitorThread::CTestRunMonitorThread(void)
{
	m_wszProcessFileName[0] = _T('\0');
}

CTestRunMonitorThread::~CTestRunMonitorThread(void)
{
	Stop(); //stop if any
}

void CTestRunMonitorThread::Start(HWND hWnd, UINT unNotifyMsg, DWORD dwProcess)
{
	Stop(); //stop if any

	DWORD dwId;
	m_hWnd = hWnd;
	m_unNotifyMsg = unNotifyMsg;

	m_csProcess.Attach(OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION | PROCESS_VM_READ , FALSE, dwProcess));
	if (m_csProcess.m_h)
	{
		m_csMonitorThread.Attach(CreateThread(NULL, 0, MonitorProc, (LPVOID)this, 0, &dwId));
		if (m_csMonitorThread.m_h)
		{
			SetThreadPriority(m_csMonitorThread.m_h, THREAD_PRIORITY_BELOW_NORMAL);
			GetModuleFileNameExW(m_csProcess, NULL, m_wszProcessFileName, _countof(m_wszProcessFileName));
		}
	}
}

void CTestRunMonitorThread::Stop()
{
	if (m_csMonitorThread.m_h)
	{
		TerminateThread(m_csMonitorThread, 0);
		m_csMonitorThread.Close();
	}
	m_csProcess.Close();
	m_wszProcessFileName[0] = _T('\0');
}

DWORD WINAPI CTestRunMonitorThread::MonitorProc(LPVOID lpParam)
{
	CTestRunMonitorThread * pThis = (CTestRunMonitorThread *)lpParam;
	DWORD dwRet = WaitForSingleObject(pThis->m_csProcess, INFINITE);
	DWORD dwExitCode = 0;
	GetExitCodeProcess(pThis->m_csProcess, &dwExitCode);

	return PostMessage(pThis->m_hWnd, pThis->m_unNotifyMsg, dwRet, dwExitCode);
}